<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="970px" :close-on-click-modal="false"
    append-to-body @close="close">
    <div class="form-box new_form_box">


      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="80px" class="demo-ruleForm">
        <div style="margin-bottom: 10px;">
          <formSubTitVue title="订单信息"></formSubTitVue>
        </div>
        <el-form-item label="买家" prop="buyerId">
           <virtual-select
                    @change="getBuyerInfo"
                    v-model="form.buyerId"
                    :list="allUsers"
                    label="_showLabel"
                    value="userId"
                    :placeholder="'输入关键字用于搜索买家'"
                    :keeps-params="20"
                    :is-concat="false"
                    :concat-symbol="' || '"
                    :is-multiple="false"
                    :disabled="false"
                    :allow-create="false"
                     />

       
        </el-form-item>
        <el-form-item label="卖家" prop="sellerId">
            <virtual-select
                  @change="sellerChange"
                    v-model="form.sellerId"
                    :list="allUsers"
                    label="_showLabel"
                    value="userId"
                    :placeholder="'输入关键字用于搜索卖家'"
                    :keeps-params="20"
                    :is-concat="false"
                    :concat-symbol="' || '"
                    :is-multiple="false"
                    :disabled="false"
                    :allow-create="false"
                     />

       
        </el-form-item>
        <el-form-item label="包赔客服" prop="customerId">
          <el-select v-model="form.customerId" filterable clearable placeholder="请选择包赔客服" @change="customerChange">
            <el-option v-for="k in yuangongList" :key="k.userId" :label="k.nickName" :value="k.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="游戏" prop="gameId">
          <el-select v-model="form.gameId" filterable clearable placeholder="请选择游戏" @change="gameChange">
            <el-option v-for="g in gameList" :key="g.id" :label="g.name" :value="g.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="商品金额" prop="productAmount">
          <el-input v-model="form.productAmount" placeholder="请输入商品金额" @input="computeTotal" />
        </el-form-item>

        <el-form-item label="包赔费" prop="compensationFee">
          <el-input v-model="form.compensationFee" placeholder="请输入包赔费" @input="computeTotal" />
        </el-form-item>

        <el-form-item label="手续费" prop="serviceFee">
          <el-input v-model="form.serviceFee" placeholder="请输入手续费" @input="computeTotal" />
        </el-form-item>

        <el-form-item label="总金额">
          <el-input :value="formatMoney(form.totalAmount)" disabled />
        </el-form-item>

        <div style="margin: 10px 0;">
          <formSubTitVue title="其他信息"></formSubTitVue>
        </div>
        <!-- <div>
          <el-form-item label="换绑状态" prop="changeBindState">
            <el-select v-model="form.changeBindState" clearable placeholder="请选择">
              <el-option label="未换绑" :value="1" />
              <el-option label="已换绑" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="支付状态" prop="buyerPayStatus">
            <el-select v-model="form.buyerPayStatus" clearable placeholder="请选择">
              <el-option label="未支付" :value="1" />
              <el-option label="已支付" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="放款状态" prop="loanStatus">
            <el-select v-model="form.loanStatus" clearable placeholder="请选择">
              <el-option label="未放款" :value="1" />
              <el-option label="已放款" :value="2" />
              <el-option label="放款中" :value="3" />
            </el-select>
          </el-form-item>
        </div> -->
        <el-form-item label="其他信息" prop="otherInfo" class="row" style="width: 905px;">
          <el-input type="textarea" :rows="4" v-model="form.otherInfo" placeholder="请输入交易账号相关的其他信息，如区服、实名情况等" />
        </el-form-item>



        <div class="upload_img_box flex">
          <el-form-item label="换绑截图" prop="bindingScreenshot">
            <uploadImageOne v-model="form.bindingScreenshot" />
          </el-form-item>

          <el-form-item label="支付截图" prop="paymentScreenshot">
            <uploadImageOne v-model="form.paymentScreenshot" />
          </el-form-item>

          <el-form-item label="放款截图" prop="loanScreenshot">
            <uploadImageOne v-model="form.loanScreenshot" />
          </el-form-item>
        </div>
        <div >
          <div style="margin: 10px 0;">
            <formSubTitVue title="包赔信息"></formSubTitVue>
            <!-- <div>您暂无包信息</div> -->
          </div>
          <el-form-item style="width: 905px;" label="是否填写" prop="">
          <el-radio-group v-model="isBaopei">
            <el-radio :label="true">填写</el-radio>
            <el-radio :label="false">不填写</el-radio>
          </el-radio-group>
        </el-form-item>
         <div v-if="isBaopei">
          <el-form-item label="姓名">
            <el-input v-model="sellerGuaranteeForm.name" placeholder="姓名" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="sellerGuaranteeForm.idCard" placeholder="请输入卖家身份证号" />

          </el-form-item>
          <el-form-item label="手机号" >
            <el-input v-model="sellerGuaranteeForm.phoneNumber" placeholder="手机号" />
          </el-form-item>
          <el-form-item label="地址" prop="adress">
            <el-input style="width: 505px;" v-model="sellerGuaranteeForm.adress" placeholder="请输入卖家地址" />
          </el-form-item><br/>
          <el-form-item  label="卖家定位" prop="gpsAddr" v-if="sellerGuaranteeForm.gpsAddr">
            <el-input style="width: 505px;" disabled v-model="sellerGuaranteeForm.gpsAddr" placeholder="" />
          </el-form-item><br/>
           <el-form-item label="家庭人员资料" prop="familyRemark" label-width="100px">
          <el-input  style="width:790px" type="textarea" rows="6" v-model="sellerGuaranteeForm.familyRemark" placeholder="请输入家庭人员资料" />
        </el-form-item>
          <el-form-item label="其他信息" prop="otherRemark">
            <el-input style="width:810px" type="textarea" rows="4" v-model="sellerGuaranteeForm.otherRemark" placeholder="请输入其他信息备注" />
          </el-form-item>
          <div class="upload_img_box flex">
            <el-form-item class="row" label="身份证国徽面" prop="emblemIdcardImg" label-width="100px">
              <uploadImageOne v-model="sellerGuaranteeForm.emblemIdcardImg"></uploadImageOne>
            </el-form-item>
            <el-form-item class="row" label="身份证人像面" prop="faceIdcardImg"
              :class="{ 'hiddenupload': form.faceIdcardImg }" label-width="100px">
              <uploadImageOne v-model="sellerGuaranteeForm.faceIdcardImg"></uploadImageOne>
            </el-form-item>
          </div>
        </div>
         </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保 存</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { create, edit } from "@/api/interOrder/index";

import { mapGetters } from "vuex";
import gameListApi from "@/api/gameConfig/gameList";
import supplyConfigApi from "@/api/system/supplyConfig";
import baopeiApi from "@/api/retrieveManage/baopei";
import uploadImageOne from "@/components/upload/uploadImageOne.vue";
import formSubTitVue from "@/views/tenantPages/components/formSubTit.vue";
import VirtualSelect from "@/components/VirtualSelect.vue";

export default {
  name: "interOrderEditDialog",
  components: { VirtualSelect,uploadImageOne, formSubTitVue },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
       isBaopei: false,
      dialogVisible: false,
      dialogTitle: "新增中介订单",
      mode: "add",
      saving: false,
      allUsers: [],
      yuangongList: [],
      gameList: [],
      form: {
        id: "",
        buyerId: "",
        sellerId: "",
        customerId: "",
        gameId: "",
        gameName: '',
        account: "",
        productAmount: null,
        compensationFee: null,
        serviceFee: null,
        totalAmount: 0,
        otherInfo: "",
        changeBindState: 1,
        buyerPayStatus: 1,
        loanStatus: 1,
        bindingScreenshot: "",
        paymentScreenshot: "",
        loanScreenshot: "",
        compensationMaterials: "",
      },
      sellerGuaranteeForm: {

      },
      rules: {
        buyerId: [{ required: true, message: "请选择买家", trigger: "change" }],
        sellerId: [{ required: true, message: "请选择卖家", trigger: "change" }],
        customerId: [{ required: true, message: "请选择包赔客服", trigger: "change" }],
        gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
      },
      baopei: false
    };
  },
  methods: {
    open(mode = "add", row = null) {
      this.isBaopei = false;
      this.dialogTitle = mode === "add" ? "新增中介订单" : "编辑中介订单";
      this.dialogVisible = true;
      this.saving = false;
     this.mode = mode;
    
       // 定义一个初始表单对象
  const defaultForm = {
    id: "",
    buyerId: "",
    sellerId: "",
    customerId: (this.userInfo && this.userInfo.userId) || "",
    gameId: "",
    gameName: '',
    account: "",
    productAmount: null,
    compensationFee: null,
    serviceFee: null,
    totalAmount: 0,
    otherInfo: "",
    changeBindState: 1,
    buyerPayStatus: 1,
    loanStatus: 1,
    bindingScreenshot: "",
    paymentScreenshot: "",
    loanScreenshot: "",
    compensationMaterials: "",
  };
     

// 保证弹窗渲染后再重置
  this.$nextTick(() => {
    if (this.$refs.form) {
      this.$refs.form.resetFields();
    }
    // 保持响应式，不能直接替换 this.form
    if (row) {
       // 编辑时，先清空所有字段，再赋值
      Object.keys(defaultForm).forEach(key => {
        this.form[key] = row[key] || defaultForm[key];
      });
        // 清理多余字段
      Object.keys(this.form).forEach(key => {
        if (!(key in defaultForm)) {
          this.$delete(this.form, key);
        }
      });

      if (row.compensationMaterials) {
        this.isBaopei = true;
        this.sellerGuaranteeForm = JSON.parse(row.compensationMaterials);
      }
      this.computeTotal();
    } else {
     // 新建时，彻底重置所有字段
      Object.keys(defaultForm).forEach(key => {
        this.form[key] = defaultForm[key];
      });
      // 清理多余字段
      Object.keys(this.form).forEach(key => {
        if (!(key in defaultForm)) {
          this.$delete(this.form, key);
        }
      });
      this.sellerGuaranteeForm = {};
    }
  });
        if (!this.allUsers.length) this.getAllUsers();
      this.getYuangongList();
      if (!this.gameList.length) this.getGameList();
    },
    //重置方法
    reset() {
      this.form.totalAmount = 0;
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.sellerGuaranteeForm = {};
    },
    close() {
     
      this.dialogVisible = false;
    },
    getGameList() {
      gameListApi.getGameList().then((res) => {
        this.gameList = res.rows || [];
      });
    },
    getAllUsers() {
      supplyConfigApi.getAllUserList().then((res) => {
        this.allUsers = res.rows || [];
         this.allUsers = res.rows .map(u => ({
  ...u,
  _showLabel: `${u.nickName}(${u.phonenumber})`   // 拼好展示用字段
}))
            });
     
    },
    getYuangongList() {
      supplyConfigApi.getAllUserList({ userNewType: 1 }).then((res) => {
        this.yuangongList = res.rows || [];
        
         this.customerChange(this.userInfo.userId);
      });
    },
    getBuyerInfo(val) {
      const user = this.allUsers.find(item => item.userId == val);
      if (user) {
        this.form.buyerNickname = user.nickName;
      }

    },
    async sellerChange(val) {
      const user = this.allUsers.find(item => item.userId == val);
      if (user) {
        this.form.sellerNickname = user.nickName;
      }
      const info = await this.getByTypeAndBusinessId(val)
      // 
      if (!info) {
        this.isBaopei = false;
        this.$alert(
          "该卖家没有包赔信息，请提醒他进行包赔认证！",
          "提示",
          {
            confirmButtonText: "确定",
            callback: (action) => {
              this.sellerGuaranteeForm = { };
            },
          }
        );
      }else{
        this.isBaopei = true;
      }

    },
    customerChange(val) {
      const user = this.yuangongList.find(item => item.userId == val);
      if (user) {
        this.form.customerNickname = user.nickName;
      }
    },
    gameChange(val) {
      const game = this.gameList.find(item => item.id == val);
      if (game) {
        this.form.gameName = game.name;
      }
    },

    computeTotal() {
      const a = Number(this.form.productAmount || 0);
      const b = Number(this.form.compensationFee || 0);
      const c = Number(this.form.serviceFee || 0);
      this.form.totalAmount = a + b + c;
    },
    formatMoney(n) {
      if (n === 0) return "0.00";
      if (!n) return "0.00";
      return Number(n).toFixed(2);
    },

    async getByTypeAndBusinessId(userId) {
      try {
        const res = await baopeiApi.getByTypeAndBusinessId({
          type: 1,
          businessId: userId,
        });
        if (res.data) {
          this.sellerGuaranteeForm = res.data
          return res.data;
        } else {
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    safeJsonParse(str) {
      try { return str ? JSON.parse(str) : null; } catch (e) { return null; }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        this.saving = true;
        this.form.compensationMaterials = ''
        if(this.isBaopei){
          let baopeiInfo = {
            name: this.sellerGuaranteeForm.name,
            phoneNumber: this.sellerGuaranteeForm.phoneNumber,
            idCard: this.sellerGuaranteeForm.idCard,
            adress: this.sellerGuaranteeForm.adress,
            otherRemark: this.sellerGuaranteeForm.otherRemark || "",
            faceIdcardImg: this.sellerGuaranteeForm.faceIdcardImg || "",
            emblemIdcardImg: this.sellerGuaranteeForm.emblemIdcardImg || "",
            familyRemark:this.sellerGuaranteeForm.familyRemark || "",
            gpsAddr:this.sellerGuaranteeForm.gpsAddr || "",
          };
          this.form.compensationMaterials = JSON.stringify(baopeiInfo);
        }
        
        console.log(this.form);
        if (this.mode == 'add') {
          // 新建
          create(this.form).then(res => {
            this.$message.success("保存成功");
            this.$emit("submit");
            this.saving = false;
            this.dialogVisible = false;
          })
        } else {
          edit(this.form).then(res => {
            this.$message.success("保存成功");
            this.$emit("submit");
            this.saving = false;
            this.dialogVisible = false;
          })
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.mb10 {
  margin-bottom: 10px;
}

::v-deep .upload_img_box .el-form-item {
  width: 295px;
}
</style>
